package authentication.manager.impl;


import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;


import authentication.algorithm.Base64Algorithm;
import authentication.dao.TokenPersistent;
import authentication.entiy.Token;
import authentication.manager.TokenManager;
import authentication.util.StatusCode;
import authentication.util.Utils;

public class TokenMangerPersistence implements  TokenManager{

    

	private String usr = null; //用户name
    private TokenPersistent tokenDao=null;
    private HttpServletRequest request=null;
	private Base64Algorithm a = new Base64Algorithm();//策略模式
	private Date nowTime = Calendar.getInstance().getTime();
	
	public String createTokenSequence(Token token,TokenPersistent tokenDao) {
		String tokenSequence =token.getUserName()+"&ndsp"+token.getClientIp()+"&ndsp"+token.getTokenId()+"&ndsp"+token.getCreateDate()+"&ndsp"+token.getRequestDate()+"&ndsp"+token.getVaildDate()+"&ndsp"+token.getUserId();
		//生成token序列的规则
		String tokenSequencetojiami = a.getBase64ToTokenSequence(tokenSequence);
		int re=tokenDao.inertToken(token);
		if(re>0){
			return tokenSequencetojiami;
		}else{
			return null;
		}
	}
    public void setTokenPersistent(TokenPersistent tokenDao){
    	this.tokenDao =tokenDao;
    }
    public void setTokenHttpResquest(HttpServletRequest request){
    	this.request =request;
    }
	
	public Map<String, Object> getTokenInfo(String tokenSequence) {
		// TODO Auto-generated method stub
		Map<String, Object> map =checkToken(tokenSequence);
		if("0000".equals(map.get("Status"))){
			map.put("userName", this.usr);
		}
		return map;
	}

	@SuppressWarnings("finally")
	private Token getToken(String tokenWord){
		Token token =null;
		try{
			String[] tokenGroup=tokenWord.split("&ndsp");
			if(tokenGroup.length==7){
				token=new Token();
				token.setClientIp(tokenGroup[1]);
				token.setCreateDate(tokenGroup[3]);
				token.setRequestDate(tokenGroup[4]);
				token.setTokenId(tokenGroup[2]);
				token.setUserName(tokenGroup[0]);
				token.setVaildDate(tokenGroup[5]);
				token.setUserId(tokenGroup[6]);
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			return token;
		}
	}

	@SuppressWarnings("finally")
	private Properties getTokenInit(String name){
		Properties props = new Properties();
		try {
			InputStream in = this.getClass().getClassLoader().getResourceAsStream(name);
			props.load(in);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			props = null;
		} finally{
			return props;
		}

	}
	//使用token.pro里面的时间
	@SuppressWarnings("unused")
	
	public Map<String, Object> checkToken(String tokenSequence) {
		//判断令牌的合法性
		Map<String, Object> map=new HashMap<String, Object>();//返回值Map
		Properties props = getTokenInit("token.properties");
		Long invalid_time=Long.valueOf(props.getProperty("INVALID_TIME"));
		Token token=null;

		try {
			token=getToken(a.transformBase64Token(tokenSequence));
			if(token==null){
				map.put("Status", StatusCode.$1111_CODE);
				map.put("messages", StatusCode.getMessage(StatusCode.$1111_CODE));
				return map;
			}
			if(tokenDao.checkToken(token.getTokenId())==0){
				map.put("Status", StatusCode.$1111_CODE);
				map.put("messages",StatusCode.getMessage(StatusCode.$1111_CODE));
				return map;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			map.put("Status", StatusCode.$1111_CODE);
			map.put("messages", StatusCode.getMessage(StatusCode.$1111_CODE));
			return map;
		}
		if(props==null){
			map.put("Status", StatusCode.$1111_CODE);
			map.put("messages",StatusCode.getMessage(StatusCode.$1111_CODE));
			return map;
		}
		
		Date requestDated = Utils.timeStringToDate(token.getRequestDate());
		if(requestDated==null){
			map.put("Status", StatusCode.$1111_CODE);
			map.put("messages", StatusCode.getMessage(StatusCode.$1111_CODE));
			return map;
		}
		if(nowTime.getTime()-requestDated.getTime()>invalid_time){
			map.put("Status", StatusCode.$0001_CODE);
			map.put("messages", StatusCode.getMessage(StatusCode.$0001_CODE));
			return map;
		}
		String ipnow=Utils.getIpAddr(request);
/*		if(!ipnow.equals(token.getClientIp())){
			map.put("Status", StatusCode.$0002_CODE);
			map.put("messages",  StatusCode.getMessage(StatusCode.$0002_CODE));
			return map;
		}*/
		boolean result=false;
		try {
			result=updateToken(token);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("Status",  StatusCode.$0003_CODE);
			map.put("messages", StatusCode.getMessage(StatusCode.$0003_CODE));
			return map;
		}
		if(!result){
			map.put("Status", StatusCode.$0003_CODE);
			map.put("messages", StatusCode.getMessage(StatusCode.$0003_CODE));
			return map;
		}
		map.put("Status", StatusCode.$0000_CODE);
		map.put("messages", StatusCode.getMessage(StatusCode.$0000_CODE));
		this.usr = token.getUserName();
		return map;
	}
	
	public boolean updateToken(Token token) {
		// TODO Auto-generated method stub
		int i=tokenDao.updateToken(token);
		if(i==0){
			return false;
		}
		return true;
	}


}
